<template>
	<view class="wrap">
		<u-gap height="20" bg-color="#f5f5f5"></u-gap>
		<u-form class="task-form-field" :model="state" :rules="rules" ref="uForm">
			<u-form-item label="手机号码" label-width="180" prop="phonenumber">
				<u-input v-model="state.phonenumber" placeholder="请输入手机号码" :maxlength="11"></u-input>
			</u-form-item>
			<u-form-item label="邮箱" label-width="180" prop="email">
				<u-input v-model="state.email" placeholder="请输入邮箱"></u-input>
			</u-form-item>
		</u-form>
		<view class="form-footer">
			<u-button class="btn" type="primary" @click="submit">保存</u-button>
			<!-- <u-button class="btn" type="default" @click="cancel">关闭</u-button> -->
		</view>
	</view>
</template>

<script>
import ebus from '@/components/libs/ebus.js'
import { updateUserProfile } from '@/api/system/user.js'
import { getUserState } from './info.vue'

export default {
	data() {
		return {
			state: {
				id: '',
				name: '',
        roleName: '',
        deptName: '',
				sex: '',
				email: '',
				phonenumber: '',
				signature: ''
			},
			rules: {
				phonenumber: [
					{
						required: true,
						message: '请输入手机号码',
						trigger: ['change', 'blur'],
					}
				],
				email: [
					{
						required: true,
						message: '请输入邮箱',
						trigger: ['change', 'blur'],
					}
				]
			}
		};
	},

	onReady() {
		this.$refs.uForm.setRules(this.rules)
		this.getUserState()
	},

	methods: {
		getUserState,
		submit() {
			this.$refs.uForm.validate(async valid => {
				if (!valid) {
					return true
				}
				let user = this.getCurrentUser()
				try {
					let res = await updateUserProfile({
						userId: user.userId,
						phonenumber: this.state.phonenumber,
						email: this.state.email
					})
					if (String(res.code) === '200') {
						user.phonenumber = this.state.phonenumber
						user.email = this.state.email
						this.$u.toast('保存成功')
						ebus.$emit('onUpdateUser', user)
						this.goBack()
					} else {
						this.$u.toast(res.msg || '保存失败')
					}
				} catch(e) {
					this.$u.toast('保存失败')
				}
			})
		},
		cancel() {
			uni.navigateBack()
		}
	}
};
</script>
<style lang="scss">
page {
  background: #f5f5f5;
}
.u-form {
  background: #fff;
  padding: 0 15px;
}
.remind-text {
	padding: 20rpx 30rpx;
	color: #666666;
}
</style>
